<template>
  <div class="container">
    <n-drawer v-model:show="isDrawer" :width="width">
      <n-drawer-content :title="title" closable>
        <n-form
          :model="formParams"
          :rules="rules"
          ref="formRef"
          label-placement="left"
          :label-width="100"
        >
          <n-form-item label="预览图" path="avatar">
            <el-upload
              class="avatar-uploader"
              action=""
              :http-request="upload"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="formParams.img" :src="formParams.img" class="avatar" width="150" />
              <el-icon v-else>
                <Plus />
              </el-icon>
            </el-upload>
          </n-form-item>
          <n-form-item label="标题" path="title">
            <n-input placeholder="请输入标题" v-model:value="formParams.title" />
          </n-form-item>
          <n-form-item label="描述" path="des">
            <n-input placeholder="请输入描述" v-model:value="formParams.des" type="textarea" />
          </n-form-item>
          <n-form-item label="入住须知" path="notice">
            <n-input
              placeholder="请输入入住须知"
              v-model:value="formParams.notice"
              type="textarea"
            />
          </n-form-item>
          <n-form-item label="房间地址" path="address">
            <n-input placeholder="请输入地址" v-model:value="formParams.address" />
          </n-form-item>
          <n-form-item label="房间设施" path="property">
            <el-select
              v-model="formParams.proList"
              filterable
              clearable
              multiple
              placeholder="选择房间设施"
              style="width: 500px"
            >
              <el-option
                v-for="item in proOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </n-form-item>
          <n-form-item label="房间分类" path="categoryId">
            <el-select
              v-model="formParams.categoryId"
              filterable
              placeholder="选择房间分类"
              style="width: 240px"
            >
              <el-option
                v-for="item in cateOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </n-form-item>
          <n-form-item label="房间价格" path="price">
            <n-input-number
              placeholder="请输入价格"
              v-model:value="formParams.price"
              :step="10"
              :min="0"
              :precision="2"
            >
              <template #prefix> ￥ </template>
            </n-input-number>
          </n-form-item>
          <n-form-item label="剩余房间" path="rest">
            <n-input-number
              placeholder="请输入剩余房间"
              v-model:value="formParams.rest"
              :min="0"
              clearable
            />
          </n-form-item>

          <n-form-item label="最多入住人数" path="maxAdu">
            <n-input-number
              placeholder="请输入最多入住人数"
              v-model:value="formParams.maxAdu"
              :min="0"
              clearable
            />
          </n-form-item>

          <n-form-item label="房间图片" path="imgList">
            <el-upload
              v-model:file-list="formParams.imgList"
              :http-request="uploadImgToList"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </n-form-item>
        </n-form>

        <template #footer>
          <n-space>
            <n-button type="primary" :loading="subLoading" @click="formSubmit">提交</n-button>
            <n-button @click="handleReset">重置</n-button>
          </n-space>
        </template>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>
<script lang="ts" setup>
  import { defineProps, reactive, ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import {
    deleteHouseImg,
    getCategoryList,
    addHouse,
    // addHouseProperty,
    getPropertyList,
  } from '@/api/system/house';
  import axios from 'axios';
  import { ElMessage } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';
  import type { UploadProps } from 'element-plus';

  const dialogImageUrl = ref('');
  const dialogVisible = ref(false);
  const cateOption = ref<any>([]);
  const proOption = ref<any>([]);

  const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    deleteHouseImg(uploadFile.name);
    console.log(uploadFile, uploadFiles);
  };

  const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!;
    dialogVisible.value = true;
  };

  const rules = {
    label: {
      required: true,
      message: '请输入标题',
      trigger: 'blur',
    },
    path: {
      required: true,
      message: '请输入路径',
      trigger: 'blur',
    },
  };

  defineProps({
    title: {
      type: String,
      default: '新增房间',
    },
    width: {
      type: Number,
      default: 650,
    },
  });

  const message = useMessage();
  const formRef: any = ref(null);
  const defaultValueRef = () => ({
    title: '',
    address: '',
    des: '',
    id: 0,
    price: 0.0,
    rest: 0,
    img: '',
    imgList: [],
    categoryId: null,
    categoryValue: '',
    notice: '',
    proList: [],
    maxAdu: 0,
  });
  let isDrawer = ref(false);
  let subLoading = ref(false);
  let formParams = reactive({
    title: '',
    address: '',
    des: '',
    id: 0,
    price: 0.0,
    rest: 0,
    img: '',
    imgList: [],
    categoryId: null,
    categoryValue: '',
    notice: '',
    proList: [],
    maxAdu: 0,
  });

  async function openDrawer() {
    isDrawer.value = true;
    await getCategoryList().then((res: any) => {
      cateOption.value = res;
    });
    await getPropertyList().then((res: any) => {
      proOption.value = res;
    });
  }

  defineExpose({
    openDrawer,
  });

  function closeDrawer() {
    isDrawer.value = false;
  }

  const formSubmit = () => {
    formRef.value.validate(async (errors) => {
      if (!errors) {
        // let houseImgObj = {};
        console.log(formParams);
        await addHouse(formParams);
        message.success('添加成功');
        // handleReset();
        closeDrawer();
      } else {
        message.error('请填写完整信息');
      }
    });
  };

  function handleReset() {
    formRef.value.restoreValidation();
    formParams = Object.assign(formParams, defaultValueRef());
  }

  function beforeAvatarUpload(rawFile: any) {
    const types = ['image/jpeg', 'image/jpg', 'image/png'];
    const isImage = types.includes(rawFile.type);
    if (!isImage) {
      ElMessage.error('图片必须是jpg或png格式!');
      return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('图片不能超过2MB!');
      return false;
    }
    return true;
  }

  async function upload(param: any) {
    const formData = new FormData();
    formData.append('file', param.file);
    const url = 'http://localhost:7777/uploadFile';
    axios
      .post(url, formData)
      .then((data: any) => {
        if (data.data.code == 200) {
          message.success('上传成功');
          formParams.img = data.data.result;
        }
      })
      .catch((error: any) => {
        console.log(error);
      });
  }

  async function uploadImgToList(param: any) {
    const formData = new FormData();
    formData.append('file', param.file);
    const url = 'http://localhost:7777/uploadFile';
    axios
      .post(url, formData)
      .then((data: any) => {
        if (data.data.code == 200) {
          message.success('上传成功');
          formParams.imgList.push(data.data.result);
        }
      })
      .catch((error: any) => {
        console.log(error);
      });
  }
</script>
<style lang="less" scoped></style>
